//
//  _iOSUtils_UIImageAddtions.m
//  iOSUtils
//
//  Created by HJC on 11-9-9.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "_iOSUtils_UIImageAddtions.h"





////////////////////////////////
@implementation UIImage(_iOSUtils_Addtions) 


+ (UIImage*) imageNamed:(NSString *)name useCache:(BOOL)useCache
{
    // 默认的imageNamed函数已经应用了缓存，直接调用
    if (useCache)
    {
        return [UIImage imageNamed:name];
    }
    
    // 取得屏幕的缩放比
    CGFloat screenScale = 1.0f;
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
    {
        screenScale = [UIScreen mainScreen].scale;
    }
    
    
    // 如果scale > 1.0f，优先采用有2x结尾的图片
    NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
    NSString* path = nil; 
    if (screenScale > 1.0f)
    {
        NSString* pathExtension = [name pathExtension];
        NSString* name2x = [name stringByAppendingString:@"@2x"];
        name2x = [name2x stringByAppendingPathExtension:pathExtension];
        
        path = [resourcePath stringByAppendingPathComponent:name2x]; 
       
        // 判断@2x的图片是否存在
        BOOL isDirectory = NO; 
        if (![[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDirectory] 
            || isDirectory)
        {
            path = [resourcePath stringByAppendingPathComponent:name];
        }
    }
    else
    {
        path = [resourcePath stringByAppendingPathComponent:name];
    }
    
    return [UIImage imageWithContentsOfFile:path];
}



@end